<?php

namespace Home\Controller;

use Common\Model\OrderModel;
use Home\Event\WeixinEvent;
use Home\Model\GoodsModel;
use Org\Net\Http;
use Think\Controller;
use Home\Model\B2cOrdersModel;
use Home\Event\LetterEvent;
use Think\Exception;
use Think\Model;

//set_time_limit(100);


class MemberController extends BaseController
{
    public $obj;
    public $obj_order;
    public $member_id;

    public function __construct()
    {
        parent::__construct();
        //$this->obj = A('WeixinWeb','Event');
        //$this->obj = new \Home\Event\LetterEvent();
        $this->obj = M('b2c_members');
        $this->obj_order = new B2cOrdersModel();
        $this->member_id = $this->member_data['member_id'];


        if (!$this->member_id) {
            //$this->error('未登录，请登录！',url('Login/index'));
            $login = new LetterController();
            $status = $login->verify(1);
            if ($status === false) {
                $this->redirect('Login/index');
            }
        }
    }

    public function index()
    {

        //dump($_SESSION);die;

        $menber_data = $this->obj->where(['member_id' => $this->member_id])->find();
        // 待发货
        $no_sum = $this->obj_order->countList(0, $this->member_id);
        // 待收货
        $yes_sum = $this->obj_order->countList(10, $this->member_id);
        // 待评价
        $no_evaluate_sum = $this->obj_order->countList(8, $this->member_id);
        // 未支付
        $no_pay_sum = $this->obj_order->countList(3, $this->member_id);
        // 退款
        $refund_sum = $this->obj_order->countList(7, $this->member_id);
        //我的礼券总共
        $cuCoupon = $this->isListCoupon();
        //头像
        $user_top_img = session('t_userInfo')['logo'];
        $this->assign('user_top_img', $user_top_img);

        $this->assign('menber_data', $menber_data);
        $this->assign('cuCoupon', $cuCoupon);
        $this->assign('no_sum', $no_sum);
        $this->assign('yes_sum', $yes_sum);
        $this->assign('no_evaluate_sum', $no_evaluate_sum);
        $this->assign('no_pay_sum', $no_pay_sum);
        $this->assign('refund_sum', $refund_sum);
        $this->display();
    }

    //下载多媒体文件
    function saveMedia()
    {
        $media_id = I('get.media_id') or $this->ajaxReturn(['status' => false, 'msg' => '参数错误', 'data' => '']);
        $access_token = accessToken();
        $url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={$access_token}&media_id={$media_id}";
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_NOBODY, 0);    //对body进行输出。
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $package = curl_exec($ch);
        $httpinfo = curl_getinfo($ch);

        curl_close($ch);
        $media = array_merge(array('mediaBody' => $package), $httpinfo);

        //求出文件格式
        preg_match('/\w\/(\w+)/i', $media["content_type"], $extmatches);
        $fileExt = $extmatches[1];
        $filename = time() . rand(100, 999) . ".{$fileExt}";
        $dirname = "./Uploads/" . date('Y-m-d') . '/';
        if (!file_exists($dirname)) {
            mkdir($dirname, 0777, true);
        }
        $status = file_put_contents($dirname . $filename, $media['mediaBody']);
        $this->ajaxReturn($status ? ['status' => true, 'msg' => '成功', 'data' => trim($dirname . $filename, '.')] : ['status' => false, 'msg' => '失败', 'data' => '']);
        //return $dirname.$filename;
    }

    /**
     * 查看用户信息
     */
    public function memberInfo()
    {
        $menber_data = $this->obj->alias('m')->field("m.*,lv.name as lv_name")
            ->join("left join " . C('DB_PREFIX') . "b2c_member_lv lv on m.member_lv_id = lv.member_lv_id")
            ->where(['m.member_id' => $this->member_id])
            ->find();
        //echo M()->_sql();
        $menber_addr = M('b2c_member_addrs')->where(['member_id' => $this->member_id, 'def_addr' => 1])->find();
        $att = str_replace("/", "", $menber_addr['area']);
        $pos = strpos($att, ":");
        if ($pos) {
            $at = explode(':', $att);
            $menber_addr['area'] = $at[1];
        } else {
            $menber_addr['area'] = $att;
        }
        //dump($menber_data);die;
        //头像
        $user_top_img = session('t_userInfo')['logo'];
        $this->assign('user_top_img', $user_top_img);
        $this->assign('menber_addr', $menber_addr);
        $this->assign('menber_data', $menber_data);
        $this->display();
    }

    /**
     * 上传用户头像
     */
    public function post_member_logo()
    {
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize = 5145728;// 设置附件上传大小
        $upload->exts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $upload->rootPath = './Uploads/'; // 设置附件上传根目录
        $upload->savePath = ''; // 设置附件上传（子）目录
        // 上传文件
        $info = $upload->upload();
        $openid = session('wx_openid');
        if (!$openid) {
            die(json_encode(['file' => '']));
        }
        if (!$info) {// 上传错误提示错误信息
            echo json_encode(['file' => '']);
        } else {// 上传成功
            foreach ($info as $file) {
                $file_url = '/Uploads/' . $file['savepath'] . $file['savename'];
                //  echo json_encode(['file' => $file_url]);exit;
                $save_logo = M('b2c_temp_user')->where(['openid' => session('wx_openid')])->save(['logo' => $file_url]);
                if ($save_logo) {
                    die(json_encode(['file' => $file_url]));
                } else {
                    die(json_encode(['file' => '']));
                }
            }
        }
    }

    /**
     * 修改用户信息
     */
    public function saveMemberInfo()
    {
        $save_data['nickname'] = I('nickname', '', 'strip_tags');
        $sex = I('sex', '', 'strip_tags');
        if ($sex == '男') {
            $save_data['sex'] = '1';
        } elseif ($sex == '女') {
            $save_data['sex'] = '0';
        } else {
            $save_data['sex'] = '2';
        }
        $age = I('birthday', '', 'strip_tags');
        if (!empty($age)) {
            $birthday = explode('-', $age);
            if (!$birthday[0] || !$birthday[1] || !$birthday[2]) {
                exit(json_encode(['stat' => false, 'msg' => '时间格式错误']));
            }
            $save_data['b_year'] = $birthday[0];
            $save_data['b_month'] = $birthday[1];
            $save_data['b_day'] = $birthday[2];
        }

        $menber_stat = $this->obj->where(['member_id' => $this->member_id])->save($save_data);

        exit($menber_stat === false ? json_encode(['stat' => false, 'msg' => '修改失败']) : json_encode(['stat' => true, 'msg' => '修改成功']));
    }

    /**
     * 个人中心订单
     */
    public function memberOrder()
    {
        $view = I('view');
        if ($view === '' || !is_numeric($view)) {
            $this->error('参数不对！');
        }

        $data = $this->obj_order->orderList($view, $this->member_id);
        $this->assign('data', $data['list']);
        $this->assign('view', $view);
        $this->display('Member/memberOrder');
    }

    public function memberOrderInterface()
    {
        $view = I('get.view');
        $page = I('get.page');
        if ($view === '' || !is_numeric($view)) {
            $this->error('参数不对！');
        }
        $data = $this->obj_order->orderList($view, $this->member_id, 0, $page);

        exit(json_encode(['data' => $data['list'], 'view' => $view]));
    }

    /**
     * 订单详情
     */
    public function memberOredrData()
    {
        $order_id = I('order_id');
        //dump($order_id);
        //dump(is_numeric($order_id));die;
        if (!$order_id || !is_numeric($order_id)) {
            $this->error('参数不对！');
        }
        //$addr_data = M('b2c_member_addrs')->where(['member_id' => $this->member_id,'def_addr' => 1])->find();
        $order_data = $this->obj_order->alias('o')->field("o.*,d.logi_name,d.logi_no,s.tel")
            ->join("left join " . C('DB_PREFIX') . "b2c_delivery d on o.order_id = d.order_id")
            ->join("left join " . C('DB_PREFIX') . "webpos_local_store s on s.local_id = o.local_id")
            ->where(['o.order_id' => $order_id])->find();
        $memberData = $this->obj->where(['member_id' => $this->member_id])->find();
        $data = $this->obj_order->orderDetail($order_id);
        //dump($data);die;
        $this->assign('orderId', $order_id);
        $this->assign('memberData', $memberData);
        $this->assign('order_data', $order_data);
        $this->assign('data', $data);
        $this->display();
    }

    /**
     * 取消订单(删除订单)
     * 确认收货
     * stat: 1-取消订单、2-确认收货
     */
    public function cancelOrder()
    {
        $order_id = I('order_id') or exit(json_encode(['stat' => false, 'msg' => '失败']));
        $stat = I('stat', 0, 'intval');
        $save = [];
        $model = M();
        try {
            $model->execute('begin');
            switch ($stat) {
                case 1:
                    $save['status'] = 'dead';
                    $save['order_msg'] = '失效';
                    $log_text = '取消订单成功！';
                    $behavior = 'cancel';

                    //订单已取消
                    $data = M('b2c_orders')->where(['order_id' => $order_id, 'member_id' => $this->member_id])->find();
                    if ($data['status'] == 'dead') {
                        throw new \Exception('您已经取消成功！');
                    } elseif ($data['pay_status'] == '1') {
                        throw new \Exception('订单已经支付，请走售后流程！');
                    }
                    //优惠卷
                    $coupon_id_info = unserialize($data['coupon_id']);
                    foreach ($coupon_id_info as $cInfo) {
                        $isOk = M('b2c_discount_coupon_code')->save(['id' => $cInfo['coupon_id'], 'status' => '0', 'updated_at' => date('Y-m-d H:i:s', time())]);
                        if ($isOk === false) {
                            throw new \Exception('网络延迟，请稍后再试！');
                        }
                    }
                    //返回库存操作

                    //订单详情
                    $order_data = M('b2c_order_items i')
                        ->join("left join " . C('DB_PREFIX') . "b2c_orders o on o.order_id = i.order_id")
                        ->where(['i.order_id' => $order_id])
                        ->field("o.*,i.*")
                        ->select();
                    $m = new GoodsModel();
                    foreach ($order_data as $k => $value) {
                        $flashGoods = $m->checkGoodsIsStarBuy($value['store_pid']);
                        if (!empty($flashGoods)) {
                            //闪购商品 返回库存机制
                            $spRes = M('starbuy_flashsales_goods')->where(['id' => $flashGoods['id']])->setInc('initnum', $value['nums']);
                            $is_user_buy = M('starbuy_count_member_buy')->where(['member_id' => $this->member_id, 'fg_id' => $flashGoods['id'], 'store_pid' => $flashGoods['store_pid']])->save(['count' => 0]);
                        } else {
                            //普通商品
                            // $spRes = M('b2c_store_product')->where(['store_pid'=>$value['store_pid']])->setDec('freez',$value['nums']);
                            $old_freez = M('b2c_store_product')->where(['store_pid' => $value['store_pid']])->find()['freez'];
                            $new_freez = $old_freez - $value['nums'];
                            if ($new_freez < 0) {
                                $new_freez = 0;
                            }
                            $spRes = M('b2c_store_product')->where(['store_pid' => $value['store_pid']])->save(['freez' => $new_freez]);
                        }

                        if (!$spRes || ($is_user_buy === false)) {
                            throw new \Exception('网络延迟，请稍后再试！');
                        }
                    }
                    /***********************5-20**取消订单，返回奖金***********************/
                    if($data['bonus_pay']>0){

                        //返回奖金，并记录日志
                        $old_money = M('distribution_member')->where(['local_id'=>$data['local_id'],'member_id'=>$this->member_id])->find()['current_bonus'];
                        $new_money = $old_money + $data['bonus_pay'];
                        $res_dm =  M('distribution_member')->where(['local_id'=>$data['local_id'],'member_id'=>$this->member_id])->save(['current_bonus'=>$new_money]);
                        if($res_dm == false){ throw new \Exception('返回奖金失败');}
                        $is_add_dm_log = M('b2c_bonus_log')->add([
                            'local_id'=>$data['local_id'],
                            'member_id'=>$this->member_id,
                            'type'=>'0',
                            'change'=>'8',
                            'change_num'=>$data['bonus_pay'],
                            'param'=>$data['order_id'].','.$data['bonus_pay'],
                            'time'=>time(),
                            'msg'=>'取消订单，返回使用奖金',
                        ]);

                        if($is_add_dm_log == false){ throw new \Exception('添加返回奖金日志失败！');}
                    }
                    /****************************************************/

                    break;

                case 2:
                    $save['received_status'] = '1';
                    $save['comment_status'] = '1';
                    $save['order_msg'] = '待评价';
                    $save['received_time'] = time();
                    //订单已评价
                    $data = M('b2c_orders')->where(['order_id' => $order_id, 'member_id' => $this->member_id])->find();
                    if ($data['received_status'] == '1' && $data['comment_status'] == '1') {
                        exit(json_encode(['stat' => true, 'msg' => '成功']));
                    }
                    //物流结束
                    $d_data = M('b2c_delivery_process')->where(['order_id' => $order_id, 'item_type' => '2'])->find();
                    if (!$d_data) {
                        throw new \Exception('订单状态不对！');
                    }
                    $delivery_data = [
                        'order_id' => $d_data['order_id'],
                        'local_id' => $d_data['local_id'],
                        'mobile' => $d_data['mobile'],
                        'shipper_name' => $d_data['shipper_name'],
                        'item_type' => '3',
                        'create_time' => time(),
                    ];
                    $delivery_stat = M('b2c_delivery_process')->where(['order_id' => $order_id])->save($delivery_data);
                    if ($delivery_stat === false) {
                        throw new \Exception('订单状态不对！');
                    }
                    $delivery_stat = M('b2c_order_delivery_time')->where(['order_id' => $order_id])->save(['finish_time' => time() + 604800, 'is_task' => 1]);
                    if ($delivery_stat === false) {
                        throw new \Exception('更新收货时间失败！');
                    }
                    $log_text = '确认收货成功！';
                    $behavior = 'receive';
                    break;
                case 3:
                    $save['status'] = 'delete';
                    $save['order_msg'] = '已删除';
                    $log_text = '删除订单成功！';
                    $behavior = 'delete';
                    //订单已删除
                    $data = M('b2c_orders')->where(['order_id' => $order_id, 'member_id' => $this->member_id])->find();
                    if ($data['status'] == 'delete') {
                        exit(json_encode(['stat' => true, 'msg' => '成功']));
                    }
                    break;
                default :
                    throw new \Exception('失败');
            }

            $stat = M('b2c_orders')->where(['order_id' => $order_id, 'member_id' => $this->member_id])->save($save);
            if ($stat === false) {
                throw new \Exception('失败');
            }

            $log_data['rel_id'] = $order_id;
            $log_data['op_id'] = $this->member_id;
            $log_data['op_name'] = session('userInfo')['nickname'];
            $log_data['alttime'] = time();
            $log_data['result'] = 'SUCCESS';
            $log_data['log_text'] = $log_text;
            $log_data['behavior'] = $behavior;

            $stat = M('b2c_order_log')->add($log_data);

            //dump($stat);die;
            //throw new \Exception('失败123');
            if ($stat === false) {
                throw new \Exception('失败');
            }
            // 提交事务
            $model->execute('commit');
            exit(json_encode(['stat' => true, 'msg' => '成功']));
        } catch (\Exception $e) {
            // 事务回滚
            $model->execute('rollback');
            exit(json_encode(['stat' => false, 'msg' => $e->getMessage()]));
        }
    }



    /**
     * 支付
     */
    public function payOrder()
    {
        $type = I('type', 0);
        $order_id = I('order_id') or $this->error('参数错误');

        //$type 为真时$order_id为支付订单号
        if ($type) {
            $orders_data = $this->obj_order->where(['order_num' => $order_id])->select();
            $order_data = [];
            foreach ($orders_data as $k1 => $v1) {
                if ($v1['pay_status'] == '1') {
                    $this->error('该订单已支付！');
                }
                $order_data['total_amount'] += $v1['total_amount'];
            }
            $time = time() - $orders_data[0]['create_time'];
        } else {
            $order_data = $this->obj_order->where(['order_id' => $order_id])->find();
            //如果用户使用奖金
            $order_data['total_amount'] = bcsub($order_data['total_amount'],$order_data['bonus_pay'],2);
            if ($order_data['pay_status'] == '1') {
                $this->error('该订单已支付！');
            }
            $time = time() - $order_data['create_time'];
        }
        /* if($time > 1800){
            $this->error('订单超时！');
        }*/
        //dump($order_data);die;
        //dump($_SERVER['SERVER_NAME']);die;
        $this->assign('time', $time);
        $this->assign('order_data', $order_data);
        $this->assign('order_id', $order_id);
        $this->assign('type', $type);
        $this->display('Member/memberPayment');
    }

    public function doPayOrder()
    {
        $type = I('type', 0);
        $order_id = I('order_id') or $this->error('参数错误');
        $pay_id = (int)I('pay_id');

        $save['paymethod_id'] = $pay_id;
        $payment = '';
        $action = '';
        switch ($pay_id) {
            case 1 :
                $payment = '微信支付';
                $action = '/Pay/weixinpay/';
                $save['order_num'] = $this->createNonceStr();
                break;
            case 4 :
                $payment = '易极付';
                $action = '/Pay/yijipay/';
                $save['order_num'] = $this->createNonceStr('yjp');
                break;
        }
        if ($type) {
            $order_data = $this->obj_order->where(['order_num' => $order_id])->select();
            if (!$order_data) {
                $this->error('订单不存在');
            }
            M('b2c_order_num')->where(['order_num' => $order_id])->delete();
            $save['payment'] = $payment;
            //新增支付记录
            foreach ($order_data as $k1 => $v1) {
                $order_status = $this->addOrderNum($v1['order_id'], $save, $v1['total_amount'],$v1['bonus_pay'], $pay_id);
                if ($order_status === false) {
                    $this->error('支付失败');
                }
            }

        } else {
            $order_data = $this->obj_order->where(['order_id' => $order_id])->find();
            if (!$order_data) {
                $this->error('订单不存在');
            }
            M('b2c_order_num')->where(['order_num' => $order_data['order_num']])->delete();
            $order_status = $this->addOrderNum($order_data['order_id'], $save, $order_data['total_amount'],$order_data['bonus_pay'], $pay_id);
            if ($order_status === false) {
                $this->error('支付失败');
            }
        }

        $url = 'http://' . $_SERVER['SERVER_NAME'] . $action . 'id/' . $save['order_num'];
        //die($url);
        redirect($url);
//        dump($url);die;
//        header("location: $url");die;
        /*$url = U('Pay/weixinpay',array('id' => $save['order_num']));
        //dump($url);die;
        $this->redirect($url);*/
        //$this->redirect('Pay/weixinpay', array('id' => $save['order_num']));
    }

    /**
     * 新增一条支付记录
     * @param $order_id 订单号
     * @param $save 修改的数据
     * @param $total_amount 支付的钱
     * $pay_id 支付方式
     * @return bool
     */
    public function addOrderNum($order_id, $save, $total_amount,$bonus_pay, $pay_id)
    {
        $payData['order_num'] = $save['order_num'];
        $payData['cost_money'] = $total_amount - $bonus_pay;
        $payData['create_time'] = time();
        $payData['pay_id'] = $pay_id;
        $model = M();
        try {
            $model->startTrans();
            $inpayOk = M('b2c_order_num')->add($payData);
            if ($inpayOk === false) {
                throw new \Exception(false);
            }
            //修改订单支付单号
            $order_status = $this->obj_order->where(['order_id' => $order_id])->save($save);
            if (!$order_status) {
                throw new \Exception(false);
            }
            $model->commit();
            return true;
        } catch (\Exception $e) {
            $model->rollback();
            return false;
        }

    }

    /**
     * 生成支付单号
     * @param string $pack
     * @return string
     */
    public function createNonceStr($pack = 'wx')
    {
        $code = $pack;
        $code .= time();
        $chars = "abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $code .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        return $code;
    }

    /**
     * 物流（怡臣速配）
     */
    public function delivery()
    {
        $order_id = I('order_id') or $this->error('参数错误');
        $order_data = M('b2c_delivery_process')->alias('d')->field("d.*,s.local_name")
            ->join("left join " . C('DB_PREFIX') . "webpos_local_store s on s.local_id = d.local_id")
            ->where(['order_id' => $order_id])->select();
        $this->assign('list', $order_data);
        $this->display('Member/memberIogistics');
    }

    /**
     * 售后
     */
    public function afterSale()
    {
        $order_id = I('order_id') or $this->error('参数错误');
        $orders = M('b2c_orders')->where(['order_id' => $order_id])->find(); // 查询订单信息

        if ($orders['ship_status'] != 1) {
            $this->error('订单没有发货不能申请售后。');
        }

        $order_data = $this->obj_order->where(['order_id' => $order_id])->find();

        // 查询订单是否存在退款、退货
        $b2c_refund_money = M('b2c_refund_money')->where(['order_id' => $order_id])->select();

        $refund = 'false';
        if ($b2c_refund_money) {
            $refund = 'true';
        }

        $this->assign('refund', $refund);

        $this->assign('member_id', $this->member_id);
        $this->assign('order_data', $order_data);


        $this->assign('order_id', order_id);
        $this->assign('orders', $orders);
        $this->display('Member/memberAfterSale');
    }

    // 退款退货记录
    public function after_sale_refund()
    {
        $order_id = I('order_id') or $this->error('参数错误');

        $order = M('b2c_orders')->where(['order_id' => $order_id])->find();

        if (empty($order)) {
            $this->error('参数错误');
        }

        $b2c_refund_money = M('b2c_refund_money');

        if ($order['refund_front_status'] > 0) {
            // 售前退款
            $refund_front = $b2c_refund_money->where(['order_id' => $order_id, 'type' => '1'])->order("id desc")->limit(1)->find();
            $this->assign('refund_front', $refund_front);
        }

        if ($order['refund_ago_money_status'] > 0) {
            // 售后退款
            $refund_ago = $b2c_refund_money->where(['order_id' => $order_id, 'type' => '2'])->order("id desc")->limit(1)->find();
            $this->assign('refund_ago', $refund_ago);
        }
        if ($order['refund_ago_goods_status'] > 0) {
            // 售后退款退货
            $refund_ago = $b2c_refund_money->where(['order_id' => $order_id, 'type' => '3'])->order("id desc")->limit(1)->find();
            $this->assign('refund_ago', $refund_ago);
        }

        $this->display();
    }

    /**
     * 资产
     */
    public function memberAssets()
    {
        $data = $this->obj->where('`member_id` = ' . $this->member_id)->find();
        //echo $this->obj->_sql();
        $this->assign('data', $data);
        $this->display();
    }

    /**
     *再次购买
     */
    public function againBuy()
    {

    }

    /**
     * 收货地址
     */
    public function memberAddress()
    {
        $addR = M('b2c_member_addrs')->where(array('member_id' => $this->member_id))->order('addr_id asc')->select();
        //echo M()->_sql();
        foreach ($addR as $k => $item) {
            $att = str_replace("/", "", $item['area']);
            $pos = strpos($att, ":");
            if ($pos) {
                $at = explode(':', $att);
                $addR[$k]['area'] = $at[1];
            } else {
                $addR[$k]['area'] = $att;
            }
        }
        //dump($addR);die;
        $this->assign('addList', $addR);
        $this->display();
    }

    /**
     * 删除地址
     */
    public function deleteAddr()
    {
        $addrId = I('addrId', 0, 'intval');
        if (!$addrId) {
            $this->error('参数错误');
        }
        $stat = M('b2c_member_addrs')->where(['addr_id' => $addrId])->delete();
        $stat === false ? $this->error('删除失败') : $this->success('删除成功', U('memberAddress'));
    }

    /**
     * 评论
     */
    public function memberEvaluation()
    {
        $order_id = I('order_id') or $this->error('参数错误');
        $data = M('b2c_order_items')->where(['order_id' => $order_id])->select();
        $this->assign('list', $data);
        $this->assign('order_id', $order_id);
        $this->display();
    }

    public function doMemberEvaluation()
    {
        $order_id = I('order_id') or exit(json_encode(['stat' => false, 'msg' => '参数错误']));
        $list = I('list');
        foreach ($list as $k1 => $v1) {
            if (!is_numeric($v1['ctStatus']))
                exit(json_encode(['stat' => false, 'msg' => '参数错误']));
            $stat = $this->comment($v1, $order_id);
            if ($stat === false) {
                exit(json_encode(['stat' => false, 'msg' => '失败']));
            }
        }
        exit(json_encode(['stat' => true, 'msg' => '成功']));

    }

    public function comment($data, $order_id)
    {
        $model = M();
        try {
            //开启事物
            $model->execute('begin');
            //查询出订单里面的门店ID
            $local_id = $this->obj_order->where(['order_id' => $order_id])->find()['local_id'];
            //echo $this->obj_order->_sql();
            //根据门店ID查询货品ID对呀门店货品ID
            $store_pid = M('b2c_store_product')->where(['local_id' => $local_id, 'product_id' => $data['product_id']])->find()['store_pid'];
            $comment_data = [
                'product_point' => $data['product_point'],
                'logistics_point' => $data['logistics_point'],
                'type_id' => $data['ctStatus'] ? 'yes' : 'no',
                'member_id' => $this->member_id,
                'local_id' => $local_id,
                'store_pid' => $store_pid,
                'content' => $data['content'],
                'create_time' => time(),
            ];
            //dump($comment_data);
            $comment_stat = M('b2c_goods_comment')->add($comment_data);
            if ($comment_stat === false) {
                throw new \Exception(false);
            }

            //更新门店货品表的评论次数
            $store_product = M('b2c_store_product')->where(['store_pid' => $store_pid])->find();
            $product_save['comment_num'] = $store_product['comment_num'] + 1;//评论次数
            if ($data['ctStatus']) {
                $product_save['good_num'] = $store_product['good_num'] + 1;//好评次数
            } else {
                $product_save['good_num'] = $store_product['good_num'];//好评次数
            }
            //好评率
            $product_save['good_comment'] = round($product_save['good_num'] / $product_save['comment_num'], 2);
            //评分
            $product_save['grade'] = ($store_product['comment_num'] * $store_product['grade'] + $data['product_point']) / $product_save['comment_num'];
            $product_stat = M('b2c_store_product')->where(['store_pid' => $store_pid])->save($product_save);
            if ($product_stat === false) {
                throw new \Exception(false);
            }
            //修改订单状态
            $o_save_stat = $this->obj_order->where(['order_id' => $order_id])->save(['comment_status' => '2', 'order_msg' => '已评价']);
            //echo $this->obj_order->_sql();
            //dump($o_save_stat);die;
            if ($o_save_stat === false) {
                throw new \Exception(false);
            }
            // 提交事务
            $model->execute('commit');
            return true;
        } catch (\Exception $e) {
            // 事务回滚
            $model->execute('rollback');
            return false;
        }
    }

    /**
     * 投诉与建议
     */
    public function memberMyFeedback()
    {
        $this->assign('mobile', I('mobile'));
        $this->display();
    }

    public function doMemberMyFeedback()
    {

        $comment = trim(I('comment', ''));
        $mobile = I('mobile');
        if (!isMobile($mobile)) {
            echo 2;
            exit;
        }
        if (!$comment) {
            echo 2;
            exit;
        }
        $member_name = M('b2c_members')->where(['member_id' => $this->member_id])->find()['name'];
        $add_data = [
            'mobile' => $mobile,
            'feedback_type' => 'system',
            'member_id' => $this->member_id,
            'time' => time(),
            'title' => '意见反馈',
            'author' => $member_name,
            'comment' => $comment,
        ];
        $stat = M('b2c_member_feedback')->add($add_data);
        if ($stat) {
            echo 1;
        } else {
            echo 2;
        }
    }

    /**
     * 收藏（取消收藏）商品
     *  $type: y-收藏、n-取消收藏
     */
    public function productLike()
    {
        $obj = M('b2c_member_like');
        $product_id = I('product_id', 0);
        if (!$product_id || !is_numeric($product_id)) {
            exit(json_encode(['stat' => false, 'msg' => '非法参数']));
        }
        $local_id = I('local_id', 0);
        if (!$local_id || !is_numeric($local_id)) {
            exit(json_encode(['stat' => false, 'msg' => '非法参数']));
        }
        $type = I('type', 'y');
        if ($type == 'n') {
            $stat = $obj->where(['product_id' => $product_id, 'member_id' => $this->member_id, 'local_id' => $local_id])->save(['status' => 0]);
            exit(json_encode($stat === false ? ['stat' => false, 'msg' => '取消收藏失败，请稍后再试'] : ['stat' => true, 'msg' => '取消收藏成功']));
        }
        $data = $obj->where(['product_id' => $product_id, 'member_id' => $this->member_id, 'local_id' => $local_id])->find();
        if (!$data) {
            $stat = $obj->add(['product_id' => $product_id, 'member_id' => $this->member_id, 'local_id' => $local_id, 'status' => 1, 'create_time' => time()]);
        } elseif ($data['status'] == 0) {
            $stat = $obj->where(['product_id' => $product_id, 'member_id' => $this->member_id, 'local_id' => $local_id])->save(['status' => 1]);
        } else {
            exit(json_encode(['stat' => true, 'msg' => '已收藏，请勿重复收藏!']));
        }
        exit(json_encode($stat === false ? ['stat' => false, 'msg' => '收藏失败，请稍后再试'] : ['stat' => true, 'msg' => '收藏成功']));
    }

    /**
     * 收藏(取消收藏)店铺
     * $type: y-收藏、n-取消收藏
     */
    public function storeCollect()
    {

        $obj = M('b2c_member_like_store');
        $local_id = I('local_id', 0);
        //dump($local_id);die;
        if (!$local_id || !is_numeric($local_id)) {
            exit(json_encode(['stat' => false, 'msg' => '非法参数']));
        }
        $type = I('type', 'y');
        if ($type == 'n') {
            $stat = $obj->where(['member_id' => $this->member_id, 'local_id' => $local_id])->save(['status' => 0]);
            exit(json_encode($stat === false ? ['stat' => false, 'msg' => '取消收藏失败，请稍后再试'] : ['stat' => true, 'msg' => '取消收藏成功']));
        }
        $data = $obj->where(['member_id' => $this->member_id, 'local_id' => $local_id])->find();
        if (!$data) {
            $stat = $obj->add(['member_id' => $this->member_id, 'local_id' => $local_id, 'status' => 1, 'create_time' => time()]);
        } elseif ($data['status'] == 0) {
            $stat = $obj->where(['member_id' => $this->member_id, 'local_id' => $local_id])->save(['status' => 1]);
        } else {
            exit(json_encode(['stat' => true, 'msg' => '已收藏，请勿重复收藏!']));
        }

        exit(json_encode($stat === false ? ['stat' => false, 'msg' => '收藏失败，请稍后再试'] : ['stat' => true, 'msg' => '收藏成功']));
    }

    /**
     * 我喜欢
     * stat = false ,msg='错误消息'
     * 成功只有数据
     */
    public function myLike()
    {
        $type = !is_numeric(I('get.type')) ? 0 : I('get.type', 0);
        if ($type) {
            $data = M('b2c_member_like')->alias('ml')->field("ml.member_id,ml.create_time,ml.status,sp.*")
                ->join("left join " . C('DB_PREFIX') . "b2c_store_product sp on ml.local_id = sp.local_id and ml.product_id=sp.product_id")
                ->where(['ml.member_id' => $this->member_id])->select();
            $data ? exit(json_encode($data)) : exit(json_encode(['stat' => false, 'msg' => '服务器错误，请稍后再试']));
        } else {
            $data = M('b2c_member_like_store')->alias('mls')->field("mls.member_id,mls.create_time,mls.status,ls.*")
                ->join("left join " . C('DB_PREFIX') . "webpos_local_store ls on ls.local_id = mls.local_id ")
                ->where(['member_id' => $this->member_id])->select();
            $data ? exit(json_encode($data)) : exit(json_encode(['stat' => false, 'msg' => '服务器错误，请稍后再试']));
        }
    }

    /**
     * 好货
     */
    public function memberMyLikeGood()
    {
        $type = I('type', 0);
        //接口
        if ($type) {
            $data = M('b2c_member_like')->alias('ml')->field("ml.member_id,ml.create_time,ml.status,ml.like_id,sp.*,p.name p_name,ls.local_name")
                ->join("left join " . C('DB_PREFIX') . "b2c_store_product sp on ml.local_id = sp.local_id and ml.product_id=sp.product_id")
                ->join("left join " . C('DB_PREFIX') . "b2c_products p on  ml.product_id=p.product_id")
                ->join("left join " . C('DB_PREFIX') . "webpos_local_store ls on ls.local_id = ml.local_id ")
                ->where(['ml.member_id' => $this->member_id, 'status' => 1])->select();
            //失效商品
            $failure = 0;
            if ($data) {
                $ids = [];
                foreach ($data as $k1 => $v1) {
                    $ids[] = $v1['goods_id'];
                    if ($v1['store_status'] == 'false') {
                        $failure++;
                    }
                }
                $image = M('b2c_goods a')->join(C('DB_PREFIX') . 'image_image b on a.image_default_id=b.image_id', 'LEFT')->where(['a.goods_id' => ['in', $ids]])
                    ->getField('a.goods_id,l_url');
            }
            //喜欢店铺的个数
            $goodLenth = M('b2c_member_like')->where(['member_id' => $this->member_id, 'status' => 1])->count();

            $storeLenth = M('b2c_member_like_store mls')->join("inner join " . C('DB_PREFIX') . "webpos_local_store ls on ls.local_id = mls.local_id ")->where(['member_id' => $this->member_id, 'status' => 1])->count();

            exit(json_encode(['storeLenth' => $storeLenth, 'failure' => $failure, 'list' => $data, 'goodLenth' => $goodLenth, 'image' => $image]));
        }

        $this->display();
    }

    /**
     * 好店
     */
    public function memberMyLikeStore()
    {
        $type = I('type', 0);
        $obj = M('b2c_member_like_store');
        $data = $obj->alias('mls')->field("mls.like_id,mls.member_id,mls.create_time,mls.status,ls.*")
            ->join("inner join " . C('DB_PREFIX') . "webpos_local_store ls on ls.local_id = mls.local_id ")
            ->where(['member_id' => $this->member_id, 'status' => 1])->select();
        //echo $obj->_sql();
        foreach ($data as $k => $v) {
            $data[$k]['fans'] = $obj->where(['local_id' => $v['local_id'], 'status' => 1])->count();
        }
        $goodLenth = M('b2c_member_like')->where(['member_id' => $this->member_id, 'status' => 1])->count();
        //dump($data);die;
        //接口
        if ($type) {
            exit(json_encode(['goodLenth' => $goodLenth, 'list' => $data]));
        }
        /* $this->assign('goodLenth',$goodLenth);
         $this->assign('list',$data);
         $this->display();*/
    }

    /**
     * 取消收藏
     * $type : 0-店铺、1-商品
     */
    public function cancelLike()
    {
        $type = !is_numeric(I('post.type')) ? 0 : I('post.type', 0);
        $id = I('post.id');
        //dump($id);die;
        if (!$id || !is_numeric($id)) {
            exit(json_encode(['stat' => false, 'msg' => '参数错误']));
        }
        $moble = M('b2c_member_like_store');
        if ($type) {
            $moble = M('b2c_member_like');
        }
        $stat = $moble->where(['like_id' => $id])->save(['status' => 0]);
        exit(json_encode($stat === false ? ['stat' => false, 'msg' => '取消关注失败'] : ['stat' => true, 'msg' => '取消关注成功']));
    }

    /**
     * 清除喜欢的店铺或商品
     * $type : 0-店铺、1-商品
     */
    public function deleteLike()
    {
        $type = !is_numeric(I('post.type')) ? 0 : I('post.type', 0);
        $id = I('post.id');
        //dump($id);die;
        //批量清除
        if (is_array($id)) {
            $ids = '';
            foreach ($id as $k1 => $v1) {
                if (!is_numeric($v1)) {
                    exit(json_encode(['stat' => false, 'msg' => '参数错误']));
                }
                $ids .= $v1 . ',';
            }
            $ids = trim($ids, ',');
            $where['like_id'] = ['in', $ids];
        } else {
            //单个清除
            if (!$id || !is_numeric($id)) {
                exit(json_encode(['stat' => false, 'msg' => '参数错误']));
            }
            $where = ['like_id' => $id];
        }

        $moble = M('b2c_member_like_store');
        if ($type) {
            $moble = M('b2c_member_like');
        }
        $stat = $moble->where($where)->delete();
        exit(json_encode($stat === false ? ['stat' => false, 'msg' => '清除失败'] : ['stat' => true, 'msg' => '清除成功']));
    }


    //优惠卷列表页面
    public function memberCoupon()
    {

        $countList = M('b2c_discount_coupon_code cc')
            ->join("left join " . C('DB_PREFIX') . "b2c_discount_coupon dc on cc.discount_coupon_id = dc.id and cc.local_id = dc.local_id")
            ->where(['cc.status' => ['neq', '1'], 'cc.member_id' => $this->member_id, 'cc.delete_failcoupon' => 'false', 'dc.end_time' => ['gt', date('Y-m-d H:i:s', time())]])
            ->count();

        $to_coupon = $failCode = $this->time_out_coupon();

        $this->assign('countfail', count($to_coupon));
        $this->assign('count', $countList);

        $this->display();
    }

    public function apimemberCoupon()
    {
        $page = max(I('get.page'), 1);
        $num = max(I('get.num'), 10);


        $dhCode = M('b2c_discount_coupon_code cc')
            ->join("left join " . C('DB_PREFIX') . "b2c_discount_coupon dc on cc.discount_coupon_id = dc.id and cc.local_id = dc.local_id")
            ->join("left join " . C('DB_PREFIX') . "webpos_local_store ls on ls.local_id = dc.local_id")
            ->where(['cc.status' => ['neq', '1'], 'cc.member_id' => $this->member_id, 'cc.delete_failcoupon' => 'false', 'dc.end_time' => ['gt', date('Y-m-d H:i:s', time())]])
            ->field('dc.*,cc.discount_coupon_id,cc.code,cc.member_id,cc.status,dc.local_id,cc.id as cid,ls.local_name')
            ->page($page, $num)
            ->select();

        foreach ($dhCode as $k => &$value) {

            if (strtotime($value['end_time']) - time() < 86400) {
                $value['willFail'] = 1;
            } else {
                $value['willFail'] = 0;
            }
            $is_end_time = strtotime($value['end_time']);
            $is_start_time = strtotime($value['start_time']);
            $value['end_time'] = date("Y-m-d H:i", $is_end_time);
            $value['start_time'] = date("Y-m-d H:i", $is_start_time);


        }

        if (empty($dhCode)) {
            $dhCode = null;
        }


        $data = ['data' => $dhCode, 'num' => $num];

        $this->ajaxReturn($data);
    }

    //订单优惠卷使用说明
    public function memberGoodsNoUse($rule_id)
    {

        $goods_id = M('b2c_discount_coupon')->where(['id' => $rule_id, 'type' => ['in', ['1', '2']]])->find()['goods_id_array'];

        $arr_store_id = explode('#', $goods_id);
        $coupon_product = array();
        foreach ($arr_store_id as $k => $value) {
            if (!empty($value)) {
                $find_product = M('b2c_store_product sp')
                    ->join('left join sdb_b2c_products p on p.product_id = sp.product_id')
                    ->where(['sp.store_pid' => $value, 'sp.store_status' => 'true'])
                    ->field('sp.*,p.spec_info')
                    ->find();

                if ($find_product !== false && !empty($find_product)) {
                    $coupon_product[$k] = $find_product;
                }
            }
        }

        $this->assign('no_coupon_goods', $coupon_product);
        $this->display();
    }


    //可用优惠卷
    public function isListCoupon()
    {

        $dhCode = M('b2c_discount_coupon_code cc')
            ->join("left join " . C('DB_PREFIX') . "b2c_discount_coupon dc on cc.discount_coupon_id = dc.id and cc.local_id = dc.local_id")
            ->join("left join " . C('DB_PREFIX') . "webpos_local_store ls on ls.local_id = dc.local_id")
            ->where(['cc.status' => ['neq', '1'], 'cc.member_id' => $this->member_id, 'cc.delete_failcoupon' => 'false'])
            ->field('dc.*,cc.discount_coupon_id,cc.code,cc.member_id,cc.status,dc.local_id,cc.id as cid,ls.local_name')
            ->select();

        $i = 0;
        foreach ($dhCode as $k => $value) {


            if (strtotime($value['end_time']) > time()) {
                if (strtotime($value['end_time']) - time() < 86400) {
                    $value['willFail'] = 1;
                } else {
                    $value['willFail'] = 0;
                }
                $value['end_time'] = strtotime($value['end_time']);
                $canCode[$k] = $value;


            } else {
                $i++;
            }
        }

        $count = count($canCode);
        return $count;
    }

    //商品优惠卷能使用的商品
    public function memberCouponGoodsList()
    {
        $this->display();
    }


    public function apimemberCouponGoodsList($rule_id)
    {
        $page = max(I('get.page'), 1);
        $num = max(I('get.num'), 10);
        $goods_id = M('b2c_discount_coupon')->where(['id' => $rule_id, 'type' => '3'])->find()['goods_id_array'];
        $arr_store_id = explode('#', $goods_id);
        $coupon_product = array();
        foreach ($arr_store_id as $k => $value) {
            if (!empty($value)) {
                $find_product = M('b2c_store_product sp')
                    ->join('left join sdb_b2c_products p on p.product_id = sp.product_id')
                    ->where(['sp.store_pid' => $value, 'sp.store_status' => 'true'])
                    ->field('sp.*,p.spec_info')
                    ->find();


                if ($find_product !== false && !empty($find_product)) {

                    $find_product['img_path'] = getThumb($find_product['goods_id']);
                    if (empty($find_product['img_path'])) {
                        $find_product['img_path'] = getOriginalImg($find_product['goods_id']);;
                    }

                    $coupon_product[$k] = $find_product;
                }
            }
        }

        $start = ($page - 1) * $num;
        $now_product = array_slice($coupon_product, $start, $num);

        if (empty($now_product)) {
            $now_product = null;
        }

        $data = ['data' => $now_product];
        $this->ajaxReturn($data);

    }


    /**
     * 失效优惠卷
     */
    public function memberCouponFail()
    {

        $failCode = $this->time_out_coupon();

        $count = count($failCode);
        $this->assign('count', $count);

        $this->display();
    }

    public function apimemberCouponFail()
    {

        $page = max(I('get.page'), 1);
        $num = max(I('get.num'), 10);

        $failCode = $this->time_out_coupon();

        $count = count($failCode);
        $start = ($page - 1) * $num;
        $failCode = array_slice($failCode, $start, $num);
        if (empty($failCode)) {
            $failCode = null;
        }
        $data = ['data' => $failCode];
        $this->ajaxReturn($data);

    }

    /**
     * 失效优惠卷
     */
    public function time_out_coupon()
    {
        $dhCode = M('b2c_discount_coupon_code cc')
            ->join("left join " . C('DB_PREFIX') . "b2c_discount_coupon dc on cc.discount_coupon_id = dc.id and cc.local_id = dc.local_id")
            ->join("left join " . C('DB_PREFIX') . "webpos_local_store ls on ls.local_id = dc.local_id")
            ->where(['cc.status' => ['neq', '1'], 'cc.member_id' => $this->member_id,
                'cc.delete_failcoupon' => 'false'])
            ->field('dc.*,cc.discount_coupon_id,cc.code,cc.member_id,cc.status,dc.local_id,cc.id as cid,ls.local_name')
            ->select();

        foreach ($dhCode as $k => &$value) {
            if (strtotime($value['end_time']) < time()) {
                $str_time = strtotime($value['end_time']);
                $str_startime = strtotime($value['start_time']);
                $value['end_time'] = date("Y-m-d H:i", $str_time);
                $value['start_time'] = date("Y-m-d H:i", $str_startime);

                $failCode[$k] = $value;
            }
        }

        return $failCode;

    }


    /**
     * 清除失效优惠卷
     */

    public function deleteCouponFail()
    {
        $dhCode = M('b2c_discount_coupon_code cc')
            ->join("left join " . C('DB_PREFIX') . "b2c_discount_coupon dc on cc.discount_coupon_id = dc.id and cc.local_id = dc.local_id")
            ->where(['cc.status' => ['neq', '1'], 'cc.member_id' => $this->member_id,
                'cc.delete_failcoupon' => 'false'])
            ->field('dc.*,cc.discount_coupon_id,cc.code,cc.member_id,cc.status,dc.local_id,cc.id as cid')
            ->select();

        foreach ($dhCode as $k => $value) {
            if (strtotime($value['end_time']) < time()) {
                $failCode['id'][$k] = $value['cid'];

            }
        }

        $res = M('b2c_discount_coupon_code')->where(['id' => ['in', $failCode['id']]])->save(['delete_failcoupon' => 'true']);

        if ($res !== false) {
            $this->ajaxReturn(array('msg' => "清除成功！", 'status' => 1));
        } else {
            $this->ajaxReturn(array('msg' => "清除失败！", 'status' => 0));
        }


    }


    /**
     * 兑换优惠卷
     */
    public function ecCode()
    {
        $data = I();

        $dhCode = M('b2c_discount_coupon_code cc')
            ->join("left join " . C('DB_PREFIX') . "b2c_discount_coupon dc on cc.discount_coupon_id = dc.id and cc.local_id = dc.local_id")
            ->where(['cc.code' => $data['code'], 'cc.status' => ['neq', '1'], 'cc.member_id' => ['eq', 0]])
            ->field('dc.*,cc.discount_coupon_id,cc.code,cc.member_id,cc.status,dc.local_id,cc.id as cid')
            ->find();
        if (!empty($dhCode)) {
            if (strtotime($dhCode['end_time']) < time()) {
                $this->ajaxReturn(array('msg' => "优惠券已过期！", 'status' => 0));
            }

            $res = M('b2c_discount_coupon_code')->where(['id' => $dhCode['cid']])->save(['member_id' => $this->member_id, 'updated_at' => time()]);

            if ($res !== false) {
                $this->ajaxReturn(array('msg' => "恭喜您成功兑换" . $dhCode['name'] . '!', 'status' => 1));
            } else {
                $this->ajaxReturn(array('msg' => "兑换失败，再兑换一次！", 'status' => 0));
            }

        } else {
            $res_su = M('b2c_discount_coupon_code')->where(['code' => $data['code']])->find();

            if ($res_su['member_id'] != 0) {
                $this->ajaxReturn(array('msg' => "该优惠券已经被使用！", 'status' => 0));
            } else if (empty($res_su)) {
                $this->ajaxReturn(array('msg' => "请输入正确的优惠券！", 'status' => 0));
            }

        }

    }

    /*生成海报*/

    public function createPoster()
    {

        $weixinEvent = new WeixinEvent();
        //临时二维码参数


        $local_id = I('local_id') ? I('local_id') : $this->error('门店数据异常！');
        $time = date('Y/m/d H:i:s', time());

        //判断用户是否过期
        $is_ready = M('distribution_member')->where(['member_id' => $this->member_id, 'local_id' => $local_id])->find();

        if (!empty($is_ready)  && !empty($is_ready['pic_src'])) {
            //已经生成过了的
            $is_Expired = M('distribution_member')->where(['member_id' => $this->member_id, 'local_id' => $local_id, 'end_time' => ['lt', $time]])->find();

            if (empty($is_Expired)) {
                //未过期 直接调取用户生成过的海报
                //$poster_img = "/Uploads/user_poster/" . $this->member_id .$local_id. 'hp.jpg';
               $this->redirect('Poster/index',array('mid'=>$this->member_id,'lid'=>$local_id));
                return false;
            }else{
                //过期删除原图
                if(file_exists($_SERVER['DOCUMENT_ROOT'].$is_ready['pic_src'])){
                    $result = @unlink ($_SERVER['DOCUMENT_ROOT'].$is_ready['pic_src']);
                    $att = str_replace("hp.jpg", "mhp.jpg", $is_ready['pic_src']);
                    $result1 = @unlink ($_SERVER['DOCUMENT_ROOT'].$att);
                    if ($result === false && $result1 === false) {
                        $this->error('网络异常，请从新再试！');
                    }
                }


            }
        }
        $set_content = M('weixin_poster')->where(['local_id' => $local_id])->find();
        if(empty($set_content)){
            $this->error('该店铺未设置 生成海报图');
        }


        $member_name = M('b2c_members m')->join("left join sdb_b2c_temp_user tu on tu.openid = m.openid")->where(['m.member_id' => $this->member_id])
            ->field('m.nickname,tu.logo,m.openid')
            ->find();

        //文字px长度
        $fontNum = strlen($set_content['title']) / 3;
        $with = $fontNum * 40;
        $star_pos = (750 - $with) / 2;



        //图片生成水印
        $image = new \Think\Image();

        //string
        $str_content = '长 按 识 别 二 维 码 即 可';

        //string1
        $str_content1 = '海报有效期至：' . date('Y/m/d H:i:s', time() + 2592000);

        //string2
        $str_content2 = $member_name['nickname'] . $set_content['content'];

        //文字px长度2
        $fontNum1 = strlen($str_content2) / 3;
        $with1 = $fontNum1 * 44;
        $star_pos1 = (750 - $with1) / 2;


        //头像

        // 在图片左上角添加水印（水印文件位于./logo.png） 并保存为water.jpg


        if(empty($member_name['logo'])){
            $pic_url = $_SERVER['DOCUMENT_ROOT'] . '/Public/Home/images/member_headLogo.png';
        }else{

            $pos = strpos( $member_name['logo'],'wx.qlogo.cn');

            if ($pos > 0) {
                $pic_url = $member_name['logo'];

                //下载用户头像
                $pic_user_log = $_SERVER['DOCUMENT_ROOT'] . '/Uploads/user_logo/' . $this->member_id . '.jpg';

                $ch = curl_init();
                $timeout = 30;
                curl_setopt($ch, CURLOPT_URL, $pic_url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
                $file_contents = curl_exec($ch);
                curl_close($ch);

                file_put_contents($pic_user_log, $file_contents);

                $pic_url = $pic_user_log;
            } else {
                $pic_url = $_SERVER['DOCUMENT_ROOT'] . $member_name['logo'];
            }

        }

        /* 检测并创建子目录 */
        $dir = $_SERVER['DOCUMENT_ROOT'] . '/Uploads/user_logo/';
        if (!file_exists($dir)) {
            mkdir($dir);
        }
        $dir_poster = $_SERVER['DOCUMENT_ROOT'] . '/Uploads/user_poster/';
        if (!file_exists($dir_poster)) {
            mkdir($dir_poster);
        }
        $dir_barcode = $_SERVER['DOCUMENT_ROOT'] . '/Uploads/user_barcode/';
        if (!file_exists($dir_barcode)) {
            mkdir($dir_barcode);
        }

        //随机数
        $randNum = rand(1000,9999);


        $weixinEvent = new WeixinEvent();
        //临时二维码参数

        //判断用户是否过期  并保存或修改用户生成的 海报图片记录
        if (!empty($is_ready)) {
            $Mod = M();
            //如果是邀请的朋友第一次生成海报 ，给予上级奖金，推送消息
            if(empty($is_ready['pic_src']) && ($is_ready['p_member_id']> 0)){
                try{
                    $Mod->startTrans();
                    //1.给上级分发生成海报奖金
                    $sj_user = M('distribution_member')->where(['member_id'=>$is_ready['p_member_id'],'local_id'=>$is_ready['local_id']])->find();
                    if ($sj_user === false || empty($sj_user)) { throw new \Exception('查询上级分销用户失败！'); }
                    //设置的奖金
                    $gift_money =   M('store_distribution_set')->where(['local_id'=>$is_ready['local_id'],'set_name'=>'generate_poster'])->find()['set_value'];

                    if(!empty($gift_money) || $gift_money != 0){
                        //设置了下级第一次生成海报获取奖励
                        $count_bonus_new = $sj_user['count_bonus'] + $gift_money;
                        $current_bonus = $sj_user['current_bonus'] + $gift_money;
                        $sa = M('distribution_member')->where(['id'=>$sj_user['id']])->save([
                            'count_bonus' => $count_bonus_new,
                            'current_bonus' => $current_bonus,
                        ]);
                        if ($sa === false) { throw new \Exception('更新上级用户金额失败！'); }
                        //2.推送消息
                        $father = M('b2c_members')->where(['member_id'=>$sj_user['member_id']])->find();
                        $child = M('b2c_members')->where(['member_id'=>$is_ready['member_id']])->find();
                        $res_weixin = WeixinSonMemberCreatePosterToFatherMember($is_ready['local_id'],$father['openid'],$child['nickname'],$gift_money);
                        if($res_weixin['errcode'] != 0){throw new \Exception('推送消息失败！');}
                        //3.日志记录表
                        $log_add = M('b2c_bonus_log')->add([
                            'local_id'=>$sj_user['local_id'],
                            'member_id'=>$sj_user['member_id'],
                            'type'=>'0',
                            'change'=>'2',
                            'change_num'=>$gift_money,
                            'time'=>time(),
                            'msg'=>'下级首次生成海报获得奖金',
                            's_member_id'=>$this->member_id,
                        ]);
                        if ($log_add === false) { throw new \Exception('添加更改记录失败！'); }

                    }

                    //4.将海报的图片跟过期更新入库
                    $res_logo_s = M('distribution_member')->where(['id' =>$is_ready['id']])->save([
                        'pic_src' => '/Uploads/user_poster/' . $this->member_id .$local_id.$randNum. 'hp.jpg',
                        'end_time' => date('Y-m-d H:i:s', time() + 2592000),
                    ]);
                    if ($res_logo_s === false) { throw new \Exception('更新分销人员记录失败！'); }
                    $Mod->commit();
                }catch (\Exception $e){
                    $Mod->rollback();

                }

            }


            //已经生成过了的
            $is_Expired = M('distribution_member')->where(['member_id' => $this->member_id, 'local_id' => $local_id, 'end_time' => ['lt', $time]])->find();


            if (!empty($is_Expired) && !empty($is_Expired['pic_src'])) {
                //过期
                $res_logo = M('distribution_member')->where(['member_id' => $this->member_id, 'local_id' => $local_id])
                    ->save([
                        'pic_src' => '/Uploads/user_poster/' . $this->member_id .$local_id.$randNum. 'hp.jpg',
                        'end_time' => date('Y-m-d H:i:s', time() + 2592000),
                        'local_id' => $local_id,
                        'member_id' => $this->member_id,
                    ]);
            }
        } else {

            //添加生成海报记录
            $res_logo = M('distribution_member')->add([
                'local_id' => $local_id,
                'member_id' => $this->member_id,
                'p_member_id' => 0,
                'friend_num' => 0,
                'count_bonus' => 0,
                'current_bonus' => 0,
                'create_time' => date('Y-m-d H:i:s', time()),
                'wait_bonus' => 0,
                'pic_src' => '/Uploads/user_poster/' . $this->member_id . $local_id .$randNum. 'hp.jpg',
                'end_time' => date('Y/m/d H:i:s', time() + 2592000),
            ]);
            //生成分销用户ID
            $is_ready['id'] = $res_logo;
        }



        $par =  $is_ready['id'];
        $resData = $weixinEvent->tmpBarcode($par);
        $Data['tmp_barcode_img'] = $resData['ticket'];
        $Data['dataExpire'] = $resData['expire_seconds'];
        //生成的二维码 保存下来 生成缩略二维码

        $getUrl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" . urlencode($Data['tmp_barcode_img']);


        // 按照原图的比例生成一个最大为150*.150的缩略图并保存为thumbjpg
        $image->open($pic_url)->thumb(120, 120)->save($_SERVER['DOCUMENT_ROOT'] . '/Uploads/user_logo/' . $this->member_id . '.jpg');

        //入库保存用户logo图片
        $res_logo = M('b2c_temp_user')->where(['openid' => $member_name['openid']])->save(['logo_m' => '/Uploads/user_logo/' . $this->member_id . '.jpg']);
        if ($res_logo === false) {
            $this->error('生成用户小头像失败', U('Member'));
        }
        //用户小头像
        $pic_user_log = $_SERVER['DOCUMENT_ROOT'] . '/Uploads/user_logo/' . $this->member_id . '.jpg';

        //印上用户头像水印

        $last_poster = $_SERVER['DOCUMENT_ROOT'] . "/Uploads/user_poster/" . $this->member_id . $local_id . $randNum.'hp.jpg';


        if(!file_exists($_SERVER['DOCUMENT_ROOT'] . $set_content['poster_pic'])){ $this->error('店铺未设置海报背景图！'); }
        $image->open($_SERVER['DOCUMENT_ROOT'] . $set_content['poster_pic'])->water($pic_user_log, ['315px', '40px'])->save($last_poster);



        //保存二维码
        $qrcode = $_SERVER['DOCUMENT_ROOT'] . '/Uploads/user_barcode/' . $this->member_id . 'bar.jpg';
        $qrcode_m = $_SERVER['DOCUMENT_ROOT'] . '/Uploads/user_barcode/' . $this->member_id . 'bar_m.jpg';

        $content = file_get_contents($getUrl);
        file_put_contents($qrcode, $content);


        if(!file_exists($qrcode)){ $this->error('二维码不存在！'); }
        $image->open($qrcode)->thumb(300, 300)->save($qrcode_m);

        if(!file_exists($last_poster)){ $this->error('生成海报图不存在！'); }
        $image->open($last_poster)->water($qrcode_m, ['265px', '590px'])->save($last_poster);


        // 在图片右下角添加水印文字 ThinkPHP 并保存为new.jpg

        $image->open($last_poster)
            ->text($set_content['title'], $_SERVER['DOCUMENT_ROOT'] .'/Public/font/msyh.ttf', 30, '#ffffff', [$star_pos . 'px', '998px'])
            ->save($last_poster);


        $image->open($last_poster)
            ->text($str_content,  $_SERVER['DOCUMENT_ROOT'] .'/Public/font/msyh.ttf', 23, '#ffffff', ['200px', '1068px'])
            ->save($last_poster);

        $image->open($last_poster)
            ->text($str_content1,  $_SERVER['DOCUMENT_ROOT'] .'/Public/font/msyh.ttf', 22, '#ffffff', ['150px', '1127px'])
            ->save($last_poster);

        $image->open($last_poster)
            ->text($str_content2,  $_SERVER['DOCUMENT_ROOT'] .'/Public/font/msyh.ttf', 32, '#ffffff', [$star_pos1, '197px'])
            ->save($last_poster);

        $image->open($last_poster)->thumb(300, 480)->save($_SERVER['DOCUMENT_ROOT'] . '/Uploads/user_poster/' .  $this->member_id . $local_id . $randNum .'mhp.jpg');


        $this->redirect('Poster/index',array('mid'=>$this->member_id,'lid'=>$local_id));


    }


    public function __destruct()
    {
        parent::__destruct();
        unset($this->obj);
        unset($this->obj_order);
    }


    /**
     * 分销 首页
     */
    public function chooseShop()
    {
        $this->display('Member/chooseShop');
    }

    /**
     * 分销 会员 店铺列表
     */
    public function ajaxChooseShop()
    {
        $page = I('page', 1, 'intval');
        $num = I('num', 10, 'intval');
        if ($page == 0 or $num == 0) $this->ajaxReturn(['data' => [], 'num' => $num]);

        $model = M();
        $stores = $model->table(C('DB_PREFIX') . 'webpos_local_store')
            ->where(['is_self' => 0, 'is_open_distribution' => '1', 'local_status' => '1', 'local_id' => ['neq', 26]])
            ->page($page, $num)
            ->field(['local_id', 'local_name', 'local_log'])->select();

        foreach ($stores as &$store) {
            $bonusInfo = $model->table(C('DB_PREFIX') . 'distribution_member')
                ->where(['member_id' => $this->member_id, 'local_id' => $store['local_id']])
                ->field(['friend_num', 'wait_bonus', 'current_bonus'])->find();
            $store['friend_num'] = empty($bonusInfo['friend_num']) ? 0 : $bonusInfo['friend_num'];
            $store['wait_bonus'] = number_format($bonusInfo['wait_bonus'], 2, '.', '');
            $store['current_bonus'] = number_format($bonusInfo['current_bonus'], 2, '.', '');
        }

        $this->ajaxReturn([
            'data' => (empty($stores) ? null : $stores)
        ]);
    }


    /**
     *分销  会员 店铺奖金
     */
    public function memberShop()
    {
        try {
            $local_id = I('local_id', 0, 'intval');
            if ($local_id == 0) throw new Exception('参数错误');

            $model = M();

            //门店信息
            $list = $model->table(C('DB_PREFIX') . 'webpos_local_store')
                ->where(['local_id' => $local_id, 'is_self' => 0, 'is_open_distribution' => '1', 'local_status' => '1'])
                ->field(['local_id', 'local_name'])
                ->find();
            if (empty($list)) throw new Exception('参数错误' . $local_id);

            //指定门店分销信息
            $bonusInfo = $model->table(C('DB_PREFIX').'distribution_member')
                ->where(['member_id' => $this->member_id, 'local_id' => $local_id])
                ->field(['friend_num', 'wait_bonus', 'current_bonus', 'end_time'])->find();
            $list['friend_num'] = (empty($bonusInfo['friend_num']) ? 0 : $bonusInfo['friend_num']);
            $list['wait_bonus'] = number_format($bonusInfo['wait_bonus'], 2, '.', '');
            $list['current_bonus'] = number_format($bonusInfo['current_bonus'], 2, '.', '');
            $list['end_time'] = (empty($bonusInfo['end_time']) ? '' : $bonusInfo['end_time']);
            //获取会员信息
            $memberInfo = $model->table(C('DB_PREFIX').'b2c_members')
                ->where(['member_id' => $this->member_id])->field(['nickname', 'openid'])->find();
            $list['nickname'] = $memberInfo['nickname'];

            //会员头像
            $userLogo = M('b2c_temp_user')->where(['openid' => $memberInfo['openid']])->field('logo')->find();
            $list['logo'] = $userLogo['logo'];

            $this->assign('data', ['bonusInfo' => $list]);
            $this->display('Member/rewardShop');
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->error($message, I('HTTP_REFERER'), 3);
        }
    }


    /**
     * 分销  我的朋友
     */
    public function rewardInvite()
    {
        try {
            $local_id = I('local_id', 0, 'intval');
            if ($local_id == 0) throw new Exception('参数错误');
            $friend = M('distribution_member')->where(['local_id' => $local_id, 'p_member_id' => $this->member_id])
                ->field('count(id) count')->find();
            $friendTotal = empty($friend['count']) ? 0 : $friend['count'];
            $this->assign('friendTotal', $friendTotal);
            $this->display('Member/rewardInvite');
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->error($message, I('HTTP_REFERER'), 3);
        }

    }

    public function inviteAjax()
    {
        $local_id = I('get.local_id', 0, 'intval');
        $page = I('page', 1, 'intval');
        if ($local_id == 0 or $page == 0) $this->ajaxReturn([]);
        $model = M();
        $friends = $model->table(C('DB_PREFIX') . 'distribution_member')
            ->where(['local_id' => $local_id, 'p_member_id' => $this->member_id])
            ->page($page . ',10')
            ->field(['member_id', 'create_time'])->select();
        $friendsInfo = [];
        foreach ($friends as $friend) {
            $memberInfo = $this->getUserInfo($friend['member_id']);
            $friendInfo['username'] = $memberInfo['nickname'];
            $friendInfo['logo'] = $memberInfo['logo'];
            $friendInfo['time'] = $friend['create_time'];
            //下级会员带来奖金
            $sBonus = $model->table(C('DB_PREFIX').'b2c_bonus_log')
                ->where(['member_id'=>$this->member_id, 's_member_id' => $friend['member_id'], 'change' => ['in', '1,2,3,4'], 'bonus_status' => '0'])
                ->order("id desc")
                ->field('sum(change_num) bonus')->find();
            $friendInfo['jlnum'] = number_format($sBonus['bonus'], 2, '.', '');
            array_push($friendsInfo, $friendInfo);
        }
        $this->ajaxReturn([
            'data' => (empty($friendsInfo) ? null : $friendsInfo)
        ]);
    }

    /**
     * 获取会员头像，昵称
     * @param $member_id
     * @return array
     */
    private function getUserInfo($member_id)
    {
        if (empty($member_id)) return [];
        $model = M();
        $memberInfo = $model->table(C('DB_PREFIX') . 'b2c_members')->where(['member_id' => $member_id])
            ->field(['nickname', 'openid'])->find();
        if (empty($memberInfo)) return [];
        $userLogo = $model->table(C('DB_PREFIX') . 'b2c_temp_user')->where(['openid' => $memberInfo['openid']])
            ->field(['logo'])->find();
        return [
            'nickname' => $memberInfo['nickname'],
            'logo' => $userLogo['logo']
        ];
    }

    /**
     * 分销 待收奖金
     */
    public function rewardWait()
    {
        try{
            $local_id = I('local_id', 0, 'intval');
            if ($local_id == 0) throw new Exception('参数错误');
            $waitInfo = M('distribution_member')
                ->where(['local_id' => $local_id, 'member_id' => $this->member_id])
                ->field(['wait_bonus'])->find();
            $waitBonus = number_format($waitInfo['wait_bonus'], 2, '.', '');
            $this->assign('waitBonus', $waitBonus);
            $this->display('Member/rewardWait');
        }catch (Exception $exc){
            $message = $exc->getMessage();
            $this->error($message, I('HTTP_REFERER'), 3);
        }

    }

    /**
     * 分销 会员 奖金历史记录
     */
    public function rewardHistory()
    {
        try{
            $local_id = I('local_id', 0, 'intval');
            if ($local_id == 0) throw new Exception('参数错误');
            $bonusInfo = M('distribution_member')
                ->where(['member_id' => $this->member_id, 'local_id' => $local_id])
                ->field(['count_bonus', 'current_bonus'])
                ->find();
            $bonusInfo['count_bonus'] = number_format($bonusInfo['count_bonus'], 2, '.', '');
            $bonusInfo['use_bonus'] = number_format($bonusInfo['count_bonus'] - $bonusInfo['current_bonus'], 2, '.', '');
            $this->assign('bonusInfo', $bonusInfo);
            $this->display('Member/rewardHistory');
        }catch (Exception $exc){
            $message = $exc->getMessage();
            $this->error($message, I('HTTP_REFERER'), 3);
        }
    }

    /**
     * ajax 分销奖金日志
     */
    public function bonusLogAjax()
    {
        $page = I('page', 1, 'intval');
        $local_id = I('get.local_id', 0, 'intval');
        $type = I('type', '', htmlspecialchars());
        if ($page == 0 or $local_id == 0 or !in_array($type, ['wait', 'all', 'get', 'use'])) $this->ajaxReturn([]);

        if ($type == 'wait'){
            $infos = M('b2c_bonus_log a')
                ->join("left join " . C('DB_PREFIX') . "b2c_members b on a.s_member_id = b.member_id")
                ->where(['a.local_id' => $local_id, 'a.member_id' => $this->member_id, 'a.bonus_status' => '1','change' => ['in', ('3,4')]])
                ->order("id desc")
                ->page($page.',10')
                ->field(['a.change_num', 'a.msg', 'a.time', 'b.nickname'])->select();
            $waitBonus = [];
            foreach ($infos as $info){
                array_push($waitBonus, [
                    'username' => $info['nickname'],
                    'goodsname' => $info['msg'],
                    'buytime' => date('Y-m-d H:i:s', $info['time']),
                    'jlnum' => number_format($info['change_num'], 2, '.', ''),
                ]);
            }
            $this->ajaxReturn(['data' => (empty($waitBonus) ? null : $waitBonus)]);
        }else{
            $map = [
                'local_id' => $local_id,
                'member_id' => $this->member_id
            ];
            switch ($type){
                case 'use':
                    $map['change'] = '5';
                    break;
                case 'get':
                    $map['change'] = ['in', '1,2,3,4,6,7,8,9'];
                    $map['bonus_status'] = '0';
                    break;
                case 'all':
                default:
                    $map['bonus_status'] = '0';
                    break;
            }
            $model = M();

            $bonusLog = $model->table(C('DB_PREFIX').'b2c_bonus_log')
                ->where($map)->order("id desc")->page($page.',10')
                ->field(['member_id', 'change', 'change_num', 'time', 'param', 's_member_id', 'msg'])->select();
            $logs = [];
            foreach ($bonusLog as $info){
                $log['buytime'] = date('Y-m-d H:i:s', $info['time']);
                $log['jlnum'] = number_format($info['change_num'], 2, '.', '');
                if ($info['change'] == 5 or $info['change'] == 6){
                    if ($info['change'] == 5){
                        list($order_id, $use_bonus) = explode(',', $info['param']);
                        $msg = sprintf("订单号：%s  使用%s奖金抵扣了%s元", $order_id, abs((float)$log['jlnum']),abs((float)$use_bonus));
                    }else{
                        list($s_member_id,$order_id, $refund_amount) = explode(',', $info['param']);
                        $msg = "订单号： $order_id  退奖金";
                    }
                    $log['username'] = '自己';
                }else{
                    switch ($info['change']){
                        case '1':
                            $msg = '关注公众号';
                            break;
                        case '2':
                            $msg = '生成分享海报';
                            break;
                        case '3':
                        case '7':
                        case '9':
                            $msg = $info['msg'];
                            break;
                        case '4':
                            $msg = '退款 '.$info['msg'];
                            break;
                        case  '8':
                            $msg = '取消订单返还奖金'.$info['change_num'];
                            break;
                        default:
                            $msg = '';
                            break;
                    }
                    //会员信息
                    $map = ($info['change'] == 9 ? ['member_id' => $info['member_id']] : ['member_id' => $info['s_member_id']]);
                    $memberInfo = $model->table(C('DB_PREFIX').'b2c_members')
                        ->where($map)->field(['nickname'])->find();
                    $log['username'] = $memberInfo['nickname'];
                }
                $log['goodsname'] = $msg;
                array_push($logs, $log);
            }
            $this->ajaxReturn(['data' => (empty($logs) ? null : $logs)]);
        }
    }

    /**
     * 奖金规则
     */
    public function rewardRule()
    {
        $local_id = I('get.local_id', 0, 'intval');
        if ($local_id == 0) $this->error('参数错误');
        $list = M('store_distribution_set')->where(['local_id'=>$local_id])->field(['set_name', 'set_value'])->select();
        if (empty($list))$this->error('还未设置分销基础信息');
        $info = [];
        foreach ($list as $value){
            $info[$value['set_name']] = $value['set_value'];
        }
        $this->assign('info', $info);
        $this->display('Member/rewardRule');
    }
}
